﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;

namespace zymain
{
    public partial class FrmReader : Form
    {
        private List<string> dtypes = new List<string>();
        private List<string> DeptDms = new List<string>();
        private List<string> Levels = new List<string>();
        private string dwdms = string.Empty;
        public BindingSource BookData;
        public BindingSource ReaderData;
        private DataTable rdt = new DataTable();
        public FrmReader()
        {
            InitializeComponent();
        }

        private void AddDwkay()
        {
            string sql = "with cte as "
                + " (select 单位代码, 单位名称, 隶属, 级别, 顺序 from 读者单位  where 读者单位.级别 = 0"
                + " union all select a.单位代码, a.单位名称, a.隶属, a.级别, a.顺序 from 读者单位 a join cte b on a.隶属 = b.单位代码 )"
                + " select * from cte order by 顺序 asc";
            this.DeptDms.Clear();
            this.dwKay.Items.Clear();
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.SqlCmd = sql;
                DataTable dt = _open.GetDataTable();
                foreach(DataRow drow in dt.Rows)
                {
                    this.dwKay.Items.Add(drow["单位名称"].ToString().Trim());
                    this.DeptDms.Add(drow["单位代码"].ToString().Trim());
                }
                if (dt.Rows.Count > 0)
                    this.dwKay.SelectedIndex = 0;
            }
        }

        private void AddLevelkay()
        {
            string sql = "select 读者级别,级别代码 from 读者统计 where 级别代码 is not null and 级别代码!='' order by 级别代码";
            this.Levels.Clear();
            this.levelKay.Items.Clear();
            this.levelKay.Items.Add("所有");
            this.Levels.Add("0");
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.SqlCmd = sql;
                DataTable dt = _open.GetDataTable();
                foreach (DataRow drow in dt.Rows)
                {
                    this.levelKay.Items.Add(drow["读者级别"].ToString().Trim());
                    this.Levels.Add(drow["级别代码"].ToString().Trim());
                }
                if (dt.Rows.Count > 0)
                    this.levelKay.SelectedIndex = 0;
            }
        }

        private void AddJstj()
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                this.jstjKay.Items.Clear();
                this.dtypes.Clear();
                _open.Reset();
                _open.SqlCmd = "SELECT TOP 20 COLUMN_NAME as cname,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME not like '%代码%' AND TABLE_NAME = '读者库'";
                DataTable zdt = _open.GetDataTable();
                foreach (DataRow drow in zdt.Rows)
                {
                    this.jstjKay.Items.Add(drow["cname"]);
                    this.dtypes.Add(drow["DATA_TYPE"].ToString().Trim());
                }
                if (zdt.Rows.Count > 0)
                    this.jstjKay.SelectedIndex = 0;
            }
        }

        private void FrmReader_Load(object sender, EventArgs e)
        {
            this.AddJstj();
            this.AddDwkay();
            this.AddLevelkay();
            this.pxKay.SelectedIndex = 0;
            this.ascKay.SelectedIndex = 0;
            this.typeKay.SelectedIndex = 0;
            jsPanel.Panel2Collapsed = true;
            ListBoxTool.cmbBind(this.jstjKay, 30);
            ListBoxTool.cmbBind(this.jsfsKay, 30);
            ListBoxTool.cmbBind(this.dwKay, 30);
            ListBoxTool.cmbBind(this.levelKay, 30);
            ListBoxTool.cmbBind(this.ascKay, 30);
            ListBoxTool.cmbBind(this.pxKay, 30);
            ListBoxTool.cmbBind(this.typeKay, 30);
        }

        private void jstj_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = this.jstjKay.SelectedIndex;
            string jsfs = this.dtypes[index];
            //Console.WriteLine(jsfs);
            this.jsfsKay.Items.Clear();
            switch (jsfs)
            {
                case "char":
                    this.jsfsKay.Items.Add("完全一致");
                    this.jsfsKay.Items.Add("前方一致");
                    this.jsfsKay.Items.Add("中间一致");
                    this.jsfsKay.Items.Add("后方一致");
                    break;
                default:
                    this.jsfsKay.Items.Add("等于");
                    this.jsfsKay.Items.Add("大于");
                    this.jsfsKay.Items.Add("小于");
                    this.jsfsKay.Items.Add("介于");
                    break;
            }
            this.jsfsKay.SelectedIndex = 0;
        }

        private void dr_CheckedChanged(object sender, EventArgs e)
        {
            if (drCheck.Checked)
            {
                jsPanel.Panel2Collapsed = false;
                this.djsKay.SelectedIndex = 0;
            }
            else
                jsPanel.Panel2Collapsed = true;
        }

        private void dwkay_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = this.dwKay.SelectedIndex;
            string dwdm = this.DeptDms[index];
            string sql = "with cte as "
                + " (select 单位代码, 单位名称, 隶属, 级别, 顺序 from 读者单位  where 读者单位.单位代码 = '" + dwdm + "' "
                + " union all select a.单位代码, a.单位名称, a.隶属, a.级别, a.顺序 from 读者单位 a join cte b on a.隶属 = b.单位代码 )"
                + " select * from cte order by 顺序 asc";
            using (DbOperHandler _open = new Common().Doh())
            {
                List<object> list = new List<object>();
                _open.Reset();
                _open.SqlCmd = sql;
                DataTable dt = _open.GetDataTable();
                foreach (DataRow drow in dt.Rows)
                {
                    list.Add(drow["单位代码"]);
                }
                this.dwdms = StringUtil.ListToString(list);
            }
        }
        System.Timers.Timer timer;
        private FrmWait wait = null;
        int total = 0;
        private void TimerUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                total++;
                Application.DoEvents();
                wait.label4.Text = "用时 【" + total + "】秒";
            }
            catch (Exception ex)
            {
                MessageBox.Show("定时事件失败:" + ex.Message);
            }
        }
        private void startTimer()
        {
            int interval = 1000;
            timer = new System.Timers.Timer(interval);
            //设置执行一次（false）还是一直执行(true)
            timer.AutoReset = true;
            //设置是否执行System.Timers.Timer.Elapsed事件
            timer.Enabled = true;
            //绑定Elapsed事件
            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerUp);
            //Console.WriteLine(interval + "");
        }
        private void ShowWait()
        {
            new Thread((ThreadStart)delegate
            {
                wait = new FrmWait();
                wait.ShowInTaskbar = false;
                Application.Run(wait);
            }).Start();
            //wait.Show();
            startTimer();
        }
        private void search()
        {
            string nr = this.jsnrTxt.Text.Trim();
            //Console.WriteLine(";;;;" + this.dwdms);
            using (DbOperHandler _open = new Common().Doh())
            {
                string sql = " 读者条码,借书证号,姓名,单位,读者级别,电话,EMAIL,联系地址,邮政编码 from 读者库 where 读者条码 is not null ";
                if (this.dwKay.SelectedIndex > 0)
                    sql += " and 单位代码 in " + this.dwdms;
                if (this.levelKay.SelectedIndex > 0)
                    sql += " and 级别代码='" + this.Levels[this.levelKay.SelectedIndex] + "' ";
                if (this.drCheck.Checked)
                {
                    string jstj = this.djsKay.Text.Trim();
                    if (this.drTxt.Lines.Length > 0)
                    {
                        string[] dztms = new string[this.drTxt.Lines.Length];
                        for (int x = 0; x < drTxt.Lines.Length; x++)
                            dztms[x] = drTxt.Lines[x].Trim();
                        string dztm = string.Empty;
                        foreach (string str in dztms)
                        {
                            if (!string.IsNullOrEmpty(str))
                                dztm += "'" + str + "',";
                        }
                        if (dztm.Length > 0)
                            dztm = dztm.Substring(0, dztm.Length - 1);
                        sql += " and " + jstj + " in (" + dztm + ") ";
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(nr))
                    {
                        sql += " and " + this.jstjKay.Text.Trim() + " ";
                        int index = this.jstjKay.SelectedIndex;
                        string ctype = this.dtypes[index];
                        switch (ctype)
                        {
                            case "char":
                                if (this.jsfsKay.SelectedIndex == 0)
                                    sql += " ='" + nr + "' ";
                                if (this.jsfsKay.SelectedIndex == 1)
                                    sql += " like '" + nr + "%' ";
                                if (this.jsfsKay.SelectedIndex == 2)
                                    sql += " like '%" + nr + "%' ";
                                if (this.jsfsKay.SelectedIndex == 3)
                                    sql += " like '%" + nr + "' ";
                                break;
                        }
                    }
                }
                if (this.typeKay.SelectedIndex > 0)
                {
                    if (this.typeKay.SelectedIndex == 1)
                        sql += " and (挂失注销 is null or 挂失注销='') ";
                    else
                        sql += " and 挂失注销='" + this.typeKay.Text.Trim() + "' ";
                }
                int xzs = Convert.ToInt32(this.numericUpDown1.Value);
                if (xzs > 0)
                    sql = " select TOP " + xzs + sql;
                sql += " order by " + this.pxKay.Text.Trim();
                if (this.ascKay.SelectedIndex == 1)
                    sql += " DESC";
                Console.WriteLine(sql);
                ShowWait();
                _open.Reset();
                _open.SqlCmd = sql;
                this.rdt = _open.GetDataTable();
                this.rdt = DTable.ViewTrim(rdt);
                this.dataGridReader.AutoGenerateColumns = false;
                this.ReaderData = new BindingSource();
                this.ReaderData.DataSource = rdt;
                this.dataGridReader.DataSource = this.ReaderData;
                if (this.ReaderData.Count > 0)
                {
                    this.photoBtn.Enabled = true;
                }
                else
                {
                    this.photoBtn.Enabled = false;
                }
                timer.Stop();
                wait.Invoke((EventHandler)delegate { wait.Close(); });
                this.dLabel.Text = "检索到 " + this.rdt.Rows.Count;
            }
        }
        private void jsnr_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar== '\r')
            {
                this.search();
            }
        }

        private void sBtn_Click(object sender, EventArgs e)
        {
            this.search();
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void photoBtn_Click(object sender, EventArgs e)
        {
            FrmRPhoto f = new FrmRPhoto();
            f.Owner = this;
            f.ShowInTaskbar = false;
            DataTable dr = new DataTable();
            dr.Columns.Add("读者条码");
            dr.Columns.Add("借书证号");
            dr.Columns.Add("姓名");
            foreach(DataRow drow in rdt.Rows)
            {
                DataRow newRow =dr.NewRow();//添加新行
                newRow["读者条码"] = drow["读者条码"];
                newRow["借书证号"] = drow["借书证号"];
                newRow["姓名"] = drow["姓名"];
                dr.Rows.Add(newRow);
            }
            f.dt = dr;
            f.Show();
        }
    }
}
